package two_to_four;

import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.Socket;

/**
 * @author Xu,
 * @data 2021/1/5，
 * @time 10:36
 */
public class Consumers4 implements Runnable{
    public static int times = 250;

    public Consumers4() {

    }

    public static void IsPrimaryNumber(long number) {
        BigInteger bigInteger = BigInteger.valueOf(number);
        bigInteger.isProbablePrime(50);
    }

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        Consumers4 c1 = new Consumers4();
        Consumers4 c2 = new Consumers4();
        Consumers4 c3 = new Consumers4();
        Consumers4 c4 = new Consumers4();
        Thread t1 = new Thread(c1);
        Thread t2 = new Thread(c2);
        Thread t3 = new Thread(c3);
        Thread t4 = new Thread(c4);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t1.join();
        t2.join();
        t3.join();
        t4.join();
        long end = System.currentTimeMillis();
        System.out.println("runtime: " + (end - start)/1000.0 + "s");
    }

    @Override
    public void run() {
        try{
            Socket socket = null;
            for(int i = 0 ; i < times; i++) {
                String host = "localhost";
                int port = 10303;
                socket = new Socket(host, port);
                String msg = "c" + " ";
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write(msg.getBytes("UTF-8"));
                InputStream inputStream = socket.getInputStream();
                byte[] bytes = new byte[1024*60];
                int len;
                StringBuilder stringBuilder = new StringBuilder();
                while((len = inputStream.read(bytes)) != -1) {
                    stringBuilder.append(new String(bytes,0,len,"UTF-8"));
                    String string = stringBuilder.toString();
                    String[] strings = string.split(" ");
                    for(int j=0;j<strings.length;j++) {
                        long number = Long.parseLong(strings[j]);
                        IsPrimaryNumber(number);
                    }
                }
                socket.shutdownInput();
                socket.shutdownOutput();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
